/**@file

 @copyright
  INTEL CONFIDENTIAL
  Copyright 2012 - 2016 Intel Corporation.

  The source code contained or described herein and all documents related to the
  source code ("Material") are owned by Intel Corporation or its suppliers or
  licensors. Title to the Material remains with Intel Corporation or its suppliers
  and licensors. The Material may contain trade secrets and proprietary and
  confidential information of Intel Corporation and its suppliers and licensors,
  and is protected by worldwide copyright and trade secret laws and treaty
  provisions. No part of the Material may be used, copied, reproduced, modified,
  published, uploaded, posted, transmitted, distributed, or disclosed in any way
  without Intel's prior express written permission.

  No license under any patent, copyright, trade secret or other intellectual
  property right is granted to or conferred upon you by disclosure or delivery
  of the Materials, either expressly, by implication, inducement, estoppel or
  otherwise. Any license under such intellectual property rights must be
  express and approved by Intel in writing.

  Unless otherwise agreed by Intel in writing, you may not remove or alter
  this notice or any other notice embedded in Materials by Intel or
  Intel's suppliers or licensors in any way.

  This file contains 'Framework Code' and is licensed as such under the terms
  of your license agreement with Intel or your vendor. This file may not be 
  modified, except as allowed by additional terms of your license agreement.

@par Specification Reference:

**/

#include "VirtualKeyboard.h"

UINT32     mOrigConOutRow      = 0;
UINT32     mOrigSetupConOutRow = 0;
extern EFI_GUID gVirtualKeyboardContextProtocolGuid;

EFI_STATUS
EFIAPI
VirtualKeyboardDriverSupported (
  IN EFI_DRIVER_BINDING_PROTOCOL      *This,
  IN EFI_HANDLE                       Controller,
  IN EFI_DEVICE_PATH_PROTOCOL         *RemainingDevicePath
  );

EFI_STATUS
EFIAPI
VirtualKeyboardDriverStart (
  IN EFI_DRIVER_BINDING_PROTOCOL      *This,
  IN EFI_HANDLE                       Controller,
  IN EFI_DEVICE_PATH_PROTOCOL         *RemainingDevicePath
  );

EFI_STATUS
EFIAPI
VirtualKeyboardDriverStop (
  IN  EFI_DRIVER_BINDING_PROTOCOL     *This,
  IN  EFI_HANDLE                      Controller,
  IN  UINTN                           NumberOfChildren,
  IN  EFI_HANDLE                      *ChildHandleBuffer
  );

/**
  Driver binding protocol support
**/
EFI_DRIVER_BINDING_PROTOCOL gVirtualKeyboardDriverBinding = {
  VirtualKeyboardDriverSupported,
  VirtualKeyboardDriverStart,
  VirtualKeyboardDriverStop,
  0x10,
  NULL,
  NULL
};

/**
  This is the declaration of an EFI image entry point. This entry point is
  the same for UEFI Applications, UEFI OS Loaders, and UEFI Drivers including
  both device drivers and bus drivers.

  @param  ImageHandle           The firmware allocated handle for the UEFI image.
  @param  SystemTable           A pointer to the EFI System Table.

  @retval EFI_SUCCESS           The operation completed successfully.
  @retval Others                An unexpected error occurred.
**/
EFI_STATUS
EFIAPI
VirtualKeyboardDriverEntryPoint (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  )
{
  EFI_STATUS                     Status;

  //
  // Install UEFI Driver Model protocol(s).
  //
  Status = EfiLibInstallDriverBindingComponentName2 (
             ImageHandle,
             SystemTable,
             &gVirtualKeyboardDriverBinding,
             ImageHandle,
             &gVirtualKeyboardComponentName,
             &gVirtualKeyboardComponentName2
             );
  ASSERT_EFI_ERROR (Status);

  mOrigConOutRow      = PcdGet32 (PcdConOutRow);
  mOrigSetupConOutRow = PcdGet32 (PcdSetupConOutRow);

  return Status;
}

/**
  Verify the controller type

  This routine determines if the pointer and GOP are available.

  This routine is called by the UEFI driver framework during connect
  processing.

  @param [in] DriverBinding        Protocol instance pointer.
  @param [in] Controller           Handle of device to test.
  @param [in] RemainingDevicePath  Not used.

  @retval EFI_SUCCESS          This driver supports this device.
  @retval other                This driver does not support this device.

**/
EFI_STATUS
EFIAPI
VirtualKeyboardDriverSupported (
  IN EFI_DRIVER_BINDING_PROTOCOL      *This,
  IN EFI_HANDLE                       Controller,
  IN EFI_DEVICE_PATH_PROTOCOL         *RemainingDevicePath
  )
{
  EFI_ABSOLUTE_POINTER_PROTOCOL *AbsolutePointer;
  VOID                          *DriverProtocol;
  EFI_GRAPHICS_OUTPUT_PROTOCOL  *GraphicsOutput;
  EFI_STATUS                    Status;

  AbsolutePointer = NULL;
  //
  // Verify that the driver is not already started
  //
  Status = gBS->OpenProtocol (
                  Controller,
                  &gVirtualKeyboardContextProtocolGuid,
                  &DriverProtocol,
                  NULL,
                  NULL,
                  EFI_OPEN_PROTOCOL_TEST_PROTOCOL
                  );
  if (!EFI_ERROR (Status)) {
    Status = EFI_ALREADY_STARTED;
    return Status;
  }

  //
  // Determine if the pointer protocol is available.
  // This should be installed in touch driver.
  //
  Status = gBS->OpenProtocol (
                  Controller,
                  &gEfiAbsolutePointerProtocolGuid,
                  (VOID**)&AbsolutePointer,
                  This->DriverBindingHandle,
                  Controller,
                  EFI_OPEN_PROTOCOL_BY_DRIVER
                  );
  if (EFI_ERROR (Status)) {
    return Status;
  }
  DEBUG (( DEBUG_INFO, "Absolute pointer protocol found\r\n" ));

  //
  // Determine if the graphics output protocol is available
  //
  Status = gBS->HandleProtocol (
                  gST->ConsoleOutHandle,
                  &gEfiGraphicsOutputProtocolGuid,
                  (VOID **)&GraphicsOutput
                  );
  if (EFI_ERROR (Status)) {
    Status = EFI_UNSUPPORTED;
  } else {
    DEBUG ((DEBUG_INFO, "Graphics output protocol found\r\n"));
  }

  gBS->CloseProtocol (
         Controller,
         &gEfiAbsolutePointerProtocolGuid,
         This->DriverBindingHandle,
         Controller
         );

  DEBUG ((DEBUG_INFO, "VirtualKeyboardDriverSupported exiting, Status: %r\n", Status));
  return Status;
}


/**
  Connect to the controller

  This routine initializes an instance of the virutal keyboard driver for this
  controller.

  This routine is called by the UEFI driver framework during connect
  processing if the controller passes the tests in I2cBusDriverSupported.

  @param [in] DriverBinding        Protocol instance pointer.
  @param [in] Controller           Handle of device to work with.
  @param [in] RemainingDevicePath  Not used, always produce all possible children.

  @retval EFI_SUCCESS          This driver is added to Controller.
  @retval other                This driver does not support this device.

**/
EFI_STATUS
EFIAPI
VirtualKeyboardDriverStart (
  IN EFI_DRIVER_BINDING_PROTOCOL      *This,
  IN EFI_HANDLE                       Controller,
  IN EFI_DEVICE_PATH_PROTOCOL         *RemainingDevicePath
  )
{
  VK_CONTEXT                     *VkContext;
  EFI_STATUS                     Status;

  //
  // Allocate the virtual keyboard context structure
  //
  VkContext = AllocateZeroPool (sizeof (VK_CONTEXT));
  if (VkContext == NULL) {
    DEBUG ((DEBUG_ERROR, "ERROR - No memory for virtual keyboard driver\r\n"));
    Status = EFI_OUT_OF_RESOURCES;
    goto ErrorExit;
  }

  //
  // Initialize the context structure
  //
  VkContext->Signature = VK_SIGNATURE;
  VkContext->Controller = Controller;

  //
  // Get the pointer protocol
  //
  Status = gBS->OpenProtocol (
                  Controller,
                  &gEfiAbsolutePointerProtocolGuid,
                  (VOID**)&VkContext->AbsolutePointer,
                  This->DriverBindingHandle,
                  Controller,
                  EFI_OPEN_PROTOCOL_BY_DRIVER
                  );
  if (EFI_ERROR (Status)) {
    DEBUG ((DEBUG_ERROR, "ERROR - Failed to open absolute pointer protocol, Status: %r\r\n", Status));
    goto ErrorExit;
  }
  Status = gBS->OpenProtocol (
                  Controller,
                  &gEfiTouchPanelGuid,
                  NULL,
                  This->DriverBindingHandle,
                  Controller,
                  EFI_OPEN_PROTOCOL_TEST_PROTOCOL
                  );
  if (EFI_ERROR (Status)) {
    DEBUG ((DEBUG_ERROR, "ERROR - TouchPanel GUID not found, Status: %r\n", Status));
    goto ErrorExit;
  }

  Status = gBS->HandleProtocol (
                  gST->ConsoleOutHandle,
                  &gEfiGraphicsOutputProtocolGuid,
                  (VOID **)&VkContext->GraphicsOutput
                  );
  if (EFI_ERROR (Status)) {
    DEBUG ((DEBUG_ERROR, "ERROR - Graphics output protocol not available, Status: %r\r\n", Status));
    goto ErrorExit;
  }

  DEBUG ((DEBUG_INFO, "0x%016Lx: Graphics output protocol found\r\n", (UINT64)(UINTN)VkContext->GraphicsOutput));

  VkContext->SimpleTextIn.Reset                = VkReset;
  VkContext->SimpleTextIn.ReadKeyStroke        = VkReadKeyStroke;

  VkContext->SimpleInputEx.Reset               = VkKeyboardResetEx;
  VkContext->SimpleInputEx.ReadKeyStrokeEx     = VkKeyboardReadKeyStrokeEx;
  VkContext->SimpleInputEx.SetState            = VkKeyboardSetState;
  VkContext->SimpleInputEx.RegisterKeyNotify   = VkKeyboardRegisterKeyNotify;
  VkContext->SimpleInputEx.UnregisterKeyNotify = VkKeyboardUnregisterKeyNotify;
//  VkContext->VkbdProtocol.ShowVkbdCallBack     = ShowVkbdCallBack;

  //
  // Install the driver protocol
  //
Status = gBS->InstallProtocolInterface (&Controller, &gVirtualKeyboardContextProtocolGuid, EFI_NATIVE_INTERFACE, (VOID**)VkContext);
DEBUG ((DEBUG_ERROR, "%r\n", Status));
Status = gBS->InstallProtocolInterface (&Controller, &gEfiSimpleTextInProtocolGuid, EFI_NATIVE_INTERFACE, (VOID**)&VkContext->SimpleTextIn);
DEBUG ((DEBUG_ERROR, "%r\n", Status));
Status = gBS->InstallProtocolInterface (&Controller, &gEfiSimpleTextInputExProtocolGuid, EFI_NATIVE_INTERFACE, (VOID**)&VkContext->SimpleInputEx);
DEBUG ((DEBUG_ERROR, "%r\n", Status));
Status = gBS->InstallProtocolInterface (&Controller, &gVirtualKeyboardProtocolGuid, EFI_NATIVE_INTERFACE, (VOID**)&VkContext->VkbdProtocol);
DEBUG ((DEBUG_ERROR, "%r\n", Status));
Status = gBS->InstallProtocolInterface (&Controller, &gEfiConsoleInDeviceGuid, EFI_NATIVE_INTERFACE, NULL);
DEBUG ((DEBUG_ERROR, "%r\n", Status));

  if (EFI_ERROR (Status)) {
    DEBUG ((DEBUG_ERROR, "ERROR - Failed to install protocols, Status: %r\r\n", Status));
    goto ErrorExit;
  }

  Status = VkApiStart (VkContext, VkContext->Controller);
  if (EFI_ERROR (Status)) {
    DEBUG ((DEBUG_ERROR, "ERROR - Failed to VkApiStart, Status: %r\r\n", Status));
    goto ErrorExit;
  }

  DEBUG ((DEBUG_INFO, "VirtualKeyboardDriverStart Success, Status: %r\r\n", Status));
  return Status;

ErrorExit:
  if (VkContext != NULL) {
    FreePool (VkContext);
  }

  gBS->CloseProtocol (
         Controller,
         &gEfiAbsolutePointerProtocolGuid,
         This->DriverBindingHandle,
         Controller
         );

//
// Restore setting if connect device fail.
//
  PcdSet32S (PcdConOutRow, mOrigConOutRow);
  PcdSet32S (PcdSetupConOutRow, mOrigSetupConOutRow);

  DEBUG ((DEBUG_LOAD, "VirtualKeyboardDriverStart Exit error, Status: %r\r\n", Status));
  return Status;
}


/**
  Disconnect from the controller.

  This routine disconnects from the controller.

  This routine is called by DriverUnload when the I2C bus driver
  is being unloaded.

  @param [in] DriverBinding        Protocol instance pointer.
  @param [in] Controller           Handle of device to stop driver on.
  @param [in] NumberOfChildren     How many children need to be stopped.
  @param [in] ChildHandleBuffer    Not used.

  @retval EFI_SUCCESS          This driver is removed Controller.
  @retval EFI_DEVICE_ERROR     The device could not be stopped due to a device error.
  @retval other                This driver was not removed from this device.

**/
EFI_STATUS
EFIAPI
VirtualKeyboardDriverStop (
  IN  EFI_DRIVER_BINDING_PROTOCOL     *This,
  IN  EFI_HANDLE                      Controller,
  IN  UINTN                           NumberOfChildren,
  IN  EFI_HANDLE                      *ChildHandleBuffer
  )
{
  VK_CONTEXT                          *VkContext;
  EFI_STATUS                          Status;

  DEBUG ((DEBUG_LOAD, "VirtualKeyboardDriverStop enter\r\n"));
  //
  // Locate the context structure
  //
  Status = gBS->OpenProtocol (
                  Controller,
                  &gVirtualKeyboardContextProtocolGuid,
                  (VOID**)&VkContext,
                  This->DriverBindingHandle,
                  Controller,
                  EFI_OPEN_PROTOCOL_BY_DRIVER | EFI_OPEN_PROTOCOL_EXCLUSIVE
                  );
  if (EFI_ERROR (Status)) {
    return EFI_SUCCESS;
  }

  //
  // Done with the driver protocol
  //
  Status = gBS->CloseProtocol (
                  Controller,
                  &gVirtualKeyboardContextProtocolGuid,
                  This->DriverBindingHandle,
                  Controller
                  );
  if (EFI_ERROR (Status)) {
    DEBUG ((DEBUG_ERROR, "ERROR - Failed to close the driver protocol, Status: %r\r\n", Status));
    return Status;
  }

  //
  // Remove ConsoleIn protocols first to close the link in ConSplitter
  //
  Status = gBS->OpenProtocol (
                  Controller,
                  &gEfiConsoleInDeviceGuid,
                  NULL,
                  This->DriverBindingHandle,
                  Controller,
                  EFI_OPEN_PROTOCOL_TEST_PROTOCOL
                  );
  if (!EFI_ERROR (Status)) {
    Status = gBS->UninstallMultipleProtocolInterfaces (
                    Controller,
                    &gEfiConsoleInDeviceGuid,
                    NULL,
                    NULL
                    );
  }

  //
  // Remove the remaining protocols
  //
  Status = gBS->UninstallMultipleProtocolInterfaces (
                  Controller,
                  &gVirtualKeyboardContextProtocolGuid,
                  (VOID**)VkContext,
                  &gEfiSimpleTextInProtocolGuid,
                  (VOID**)&VkContext->SimpleTextIn,
                  &gEfiSimpleTextInputExProtocolGuid,
                  (VOID**)&VkContext->SimpleInputEx,
                  &gVirtualKeyboardProtocolGuid,
                  (VOID**)&VkContext->VkbdProtocol,
                  NULL
                  );
  if (EFI_ERROR (Status)) {
    DEBUG ((DEBUG_ERROR, "ERROR - Failed to uninstall the protocols, Status: %r\r\n", Status));
    return Status;
  }

  //
  // Stop the driver
  //
  VkApiStop (VkContext);

  //
  // Release the pointer protocol upon failure
  //
  Status = gBS->CloseProtocol (
                  Controller,
                  &gEfiAbsolutePointerProtocolGuid,
                  This->DriverBindingHandle,
                  Controller
                  );
  if (EFI_ERROR (Status)) {
    DEBUG ((DEBUG_ERROR, "ERROR - Failed to close absolute pointer protocol, Status: %r\r\n", Status));
    return Status;
  }

  //
  // Release the context structure
  //
  FreePool (VkContext);

  DEBUG ((DEBUG_LOAD, "VirtualKeyboardDriverStop exiting, Status: %r\r\n", Status));
  return Status;
}


/**
  Unloads an image.

  @param  ImageHandle           Handle that identifies the image to be unloaded.

  @retval EFI_SUCCESS           The image has been unloaded.
  @retval EFI_INVALID_PARAMETER ImageHandle is not a valid image handle.

**/
EFI_STATUS
EFIAPI
VirtualKeyboardDriverUnload (
  IN EFI_HANDLE  ImageHandle
  )
{
  EFI_STATUS  Status;
  EFI_HANDLE  *HandleBuffer;
  UINTN       HandleCount;
  UINTN       Index;

  Status = EFI_SUCCESS;
  //
  // Retrieve array of all handles in the handle database
  //
  Status = gBS->LocateHandleBuffer (
                  AllHandles,
                  NULL,
                  NULL,
                  &HandleCount,
                  &HandleBuffer
                  );
  if (EFI_ERROR (Status)) {
    return Status;
  }

  //
  // Disconnect the current driver from handles in the handle database
  //
  for (Index = 0; Index < HandleCount; Index++) {
    Status = gBS->DisconnectController (HandleBuffer[Index], ImageHandle, NULL);
  }

  //
  // Free the array of handles
  //
  FreePool (HandleBuffer);

  //
  // Uninstall protocols installed in the driver entry point
  //
  Status = gBS->UninstallMultipleProtocolInterfaces (
                  ImageHandle,
                  &gEfiDriverBindingProtocolGuid,  &gVirtualKeyboardDriverBinding,
                  &gEfiComponentNameProtocolGuid,  &gVirtualKeyboardComponentName,
                  &gEfiComponentName2ProtocolGuid, &gVirtualKeyboardComponentName2,
                  NULL
                  );
  if (EFI_ERROR (Status)) {
    return Status;
  }

  //
  // Do any additional cleanup that is required for this driver
  //
  DEBUG ((DEBUG_LOAD, "VirtualKeyboardDriverUnload exit (%r)\r\n", Status));
  return EFI_SUCCESS;
}
